<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="凭证号" prop="voucherNo">
        <el-input
          v-model="queryParams.voucherNo"
          placeholder="请输入凭证号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="日期" prop="voucherDate">
        <el-date-picker
          v-model="queryParams.voucherDate"
          type="date"
          placeholder="选择日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:voucher:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:voucher:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:voucher:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:voucher:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="voucherList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="日期" align="center" prop="voucherDate" width="120" />
      <el-table-column label="凭证号" align="center" prop="word" width="100" />
      <el-table-column label="摘要" align="center" prop="remark" min-width="120" />
      <el-table-column label="科目" align="center" prop="subjectName" min-width="120" />
      <el-table-column label="借方金额" align="center" prop="debitAmount" width="120">
        <template #default="scope">
          {{ scope.row.debitAmount?.toFixed(2) || '0.00' }}
        </template>
      </el-table-column>
      <el-table-column label="贷方金额" align="center" prop="creditAmount" width="120">
        <template #default="scope">
          {{ scope.row.creditAmount?.toFixed(2) || '0.00' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150">
        <template #default="scope">
          <el-button type="text" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button type="text" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-show="total > 0"
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { listVoucher } from "@/api/system/voucher"
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()

// 遮罩层
const loading = ref(false)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 凭证表格数据
const voucherList = ref([])

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 50,
  voucherNo: undefined,
  voucherDate: undefined
})  

/** 查询凭证列表 */
function getList() {
  loading.value = true
  listVoucher({
    ...queryParams.value,
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize
  }).then(res => {
    if (res.code === 200) {
      voucherList.value = res.data || []
      total.value = res.total || res.data.length || 0
    }
  }).catch(() => {
    voucherList.value = []
    total.value = 0
  }).finally(() => {
    loading.value = false
  })
}

/** 分页大小改变 */
function handleSizeChange(size) {
  queryParams.value.pageSize = size
  queryParams.value.pageNum = 1
  getList()
}

/** 页码改变 */
function handleCurrentChange(page) {
  queryParams.value.pageNum = page
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    voucherNo: undefined,
    voucherDate: undefined
  }
  getList()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1  // 搜索时重置到第一页
  getList()
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  router.push('/system/voucher/voucherinsert')
}

/** 修改按钮操作 */
function handleUpdate(row) {
  router.push({
    path: '/voucher/edit',
    query: { id: row.id }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const voucherIds = row.id || ids.value

  ElMessageBox.confirm('是否确认删除选中的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    delVoucher(voucherIds).then(() => {
      getList()
      ElMessage.success('删除成功')
    })
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

/** 导出按钮操作 */
function handleExport() {
  ElMessageBox.confirm('是否确认导出所有凭证数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    exportVoucher(queryParams.value).then(response => {
      // 处理文件下载
      const blob = new Blob([response.data])
      const fileName = '凭证列表_' + new Date().getTime() + '.xlsx'
      
      if ('download' in document.createElement('a')) {
        const elink = document.createElement('a')
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href)
        document.body.removeChild(elink)
      } else {
        navigator.msSaveBlob(blob, fileName)
      }
    })
  }).catch(() => {
    ElMessage.info('已取消导出')
  })
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.mb8 {
  margin-bottom: 8px;
}
/* 优化分页样式 */
.pagination-container {
  padding: 20px 0;
  display: flex;
  justify-content: flex-end;  /* 改为右对齐 */
  background: #fff;
}
.el-pagination {
  padding: 0;
  margin: 0;
}
/* 表格样式优化 */
.el-table {
  margin-top: 15px;
}
/* 操作按钮样式 */
.el-button--text {
  margin-right: 8px;
}
.el-button--text:last-child {
  margin-right: 0;
}
</style>